package com.lishem.filenio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

/**
 * 两个Channel传输数据,大于2G的文件
 */
public class FileChannelTransferToBig2G {
    public static void main(String[] args) {
        try (FileChannel from = new FileInputStream("data.txt").getChannel();
             FileChannel to = new FileOutputStream("to.txt").getChannel()
        ) {
            // 比传统IO流效率高，底层用操作系统的零拷贝进行优化
            long size = from.size();
            // left 变量表示还剩多少字节
            for (long left = size; left > 0; ) {
                left -= from.transferTo(size - left, left, to);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
